#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2023-06-17 22:18
# @Author : hard work
import time

from test_app_main.case_cfg import snmp_oid_cfg
from common.remote_device_cfg import snmp_v1_v2_profile
from pysnmp.hlapi import *
from pysnmp.entity.rfc3413.oneliner import cmdgen

from test_app_main.case_cfg.snmp_01_oid_cfg import snmp_walk_iface_mibs

"""check ok"""


def snmpV1V2_do_get(snmp_config, oid, retry=0):
    """snmp v1 and v2 function
    # error
    """
    community_data = CommunityData(snmp_config[1], mpModel=0)
    snmp_target = UdpTransportTarget((snmp_config[0], snmp_config[2]), timeout=1, retries=retry)
    result_context_data = ContextData()
    _oid = ObjectIdentity(oid)
    obj_lst = ObjectType(_oid)
    snmpEngine = SnmpEngine()
    # 实现snmpget
    g = getCmd(snmpEngine,
               community_data,  # 团体属性
               # userData,交换机没有配认证，这里就不需要
               snmp_target,  # 创建被管理设备信息 包含IP和端口号 超时1秒 不重试
               result_context_data,  # 创建SNMP上下文信息
               obj_lst  # 创建MIB节点对象 #要跟参数 否则会报错
               )
    error_indication, errorStatus, errorIndex, varBinds = next(g)  # 发送Get请求，获取sysName

    if error_indication:  # 重传三次

        if retry < 3:
            retry += 1
            time.sleep(0.5)
            print(snmp_config[2], oid, '重试snmp_get')
            return snmpV1V2_do_get(snmp_config, oid, retry=3)
        return False
    else:
        return [x.prettyPrint() for x in varBinds]  # 列表生成器，把结果变为列表


def snmpV1V2_do_walk(snmp_config, iface_oids):
    """get multi port """
    result = {}
    cmdGen = cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorindex, varBindTable = cmdGen.bulkCmd(
        cmdgen.CommunityData(snmp_config[1]),  # 配置community
        cmdgen.UdpTransportTarget((snmp_config[0], snmp_config[2])), 0, 25, iface_oids, )
    # 配置IP地址和端口号；#0为non-repeaters 和  25为max-repetitions(一个数据包中最多25个条目，和显示无关)

    if errorIndication:
        print(errorIndication)
        return False
    elif errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorindex and varBindTable[int(errorindex) - 1][0] or '?'
        )
              )
        return False

    for varBindTableRow in varBindTable:
        for name, val in varBindTableRow:
            # print('OID:%s = %s' % (name, val))
            # result[name] = val
            result.update({name: val})
    return result


if __name__ == '__main__':
    """test snmpV1V2_do_get"""
    # snmp_cfg = snmp_v1_v2_profile()
    snmp_cfg = ["10.11.0.217", "public", 161]
    # snmp_config = snmp_config.snmp_v1_v2_config()
    snmp_case = snmp_oid_cfg.get_port_status().items()
    # print(snmpV1V2_do_get(snmp_cfg, "1.3.6.1.2.1.1.3.0")) # ok
    # for k, v in snmp_case:
    #     for i in range(1, 21):
    #         print(k, v.format(i))
    # print(snmpV1V2_do_get(snmp_cfg, "1.3.6.1.2.1.2.2.1.7.17"))
    # for k, v in snmp_walk_iface_mibs().items():
    #     # print(k, v)
    print(snmpV1V2_do_walk(snmp_cfg, "1.3.6.1.2.1.2.2.1.7.17"))
    #     for name, val in _result.items():
    #
    #         print('OID:%s = %s' % (name, val))
